<template>
    <div>
        聊天窗口
        <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
</template>

<script>
export default {
    name: "WebsocketTest",
    data(){
        return{
            ws: null,
            aa: null
        }
    },
    methods:{
        sendMessage(){
            let msg = {'toName':'1011','message':'傻逼'}
            this.ws.send(JSON.stringify(msg))
        }
    },
    created() {
        this.ws = new WebSocket('ws://localhost:8001/chat');
        this.ws.onopen = function (){
            //在建立连接后需要做什么事
            console.log('连接建立成功...')
        }

//接收服务端推送的消息后
        this.ws.onmessage = function (evt){
            //获取服务端推送过来的消息
            let dataStr = evt.data;
            let res = JSON.parse(dataStr)
            console.log('dataStr',res);
            // this.aa = res;
            //判断是否是系统消息
            if(res.isSystem){
                console.log('你有一条系统消息推送...');
                console.log('系统消息：',dataStr);
                //系统消息
                let names = res.message;
                //1、好友列表展示
                //2、系统广播的展示
                let userlistStr = '';
                let broadcastListStr = '';
            }else{
                console.log('你有一条用户消息推送...');
                //将服务端推送的消息，进行展示
                console.log('用户推送消息：',dataStr);
            }
        }

        this.ws.onclose = function (){
            //显示离线信息
            console.log('已离线...');
        }
    }
}
</script>

<style scoped>

</style>